package com.guoj.easyweb.controller;

import com.guoj.easyweb.common.exception.CustomException;
import com.guoj.easyweb.common.utils.RandomValidateCodeUtil;
import com.guoj.easyweb.common.utils.ResponseEntity;
import com.guoj.easyweb.common.utils.StatusCode;
import com.guoj.easyweb.common.validator.ValidatorUtils;
import com.guoj.easyweb.entity.TbUser;
import com.guoj.easyweb.form.LoginForm;
import com.guoj.easyweb.service.ITbUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @作者: guoj
 * @日期: 2019/6/22 09:46
 * @描述:
 */
@Controller
public class LoginController {

	@Autowired
	private ITbUserService userService;

	@PostMapping("/login")
	@ResponseBody
	public ResponseEntity login(@RequestBody LoginForm loginForm, HttpServletRequest request, HttpSession httpSession) {
		// 表单校验
		ValidatorUtils.validateEntity(loginForm);

		// 验证码校验
		String captcha = loginForm.getCaptcha();
		if (!RandomValidateCodeUtil.checkVerify(captcha, httpSession)) {
			throw new CustomException("验证码不正确", StatusCode.CAPTCHAERROR);
		}

		// 用户登录
		TbUser user = userService.login(loginForm);
		if (user == null) {
			return new ResponseEntity(false, StatusCode.LOGINERROR, "登录失败");
		}
		// 放入session
		httpSession.setAttribute("user", user);

		return new ResponseEntity(true, StatusCode.OK, "登录成功", user);
	}


	/**
	 * 检查是否登录或超时
	 * @return
	 */
	@RequestMapping(value = "/checkLogin", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity checkLogin(HttpSession session) {
		TbUser user = (TbUser) session.getAttribute("user");
		if (user == null) {
			return new ResponseEntity(false, StatusCode.SESSION_EXPIRE, "会话超时，请重新登录!");
		}
		return new ResponseEntity(true, StatusCode.OK, "正常登录状态");
	}

}
